
from archinfo import Endness

from ..utils import convert_arch
from ..shellcode import Shellcode


class X86JmpSP(Shellcode):
    os = ["cgc", "unix"]
    arches = ["X86"]
    name = "jmpsp"
    asm = "jmp esp;"
    code = b"\xff\xe4"


class AMD64JmpSP(Shellcode):

    # TODO: should be 'linux' once CLE can identify linux files
    os = ["unix"]
    arches = ["AMD64"]
    name = "jmpsp"
    asm = "jmp rsp;"
    code = b"\xff\xe4"


class ARMJmpSP(Shellcode):
    os = ["unix"]
    arches = ["ARMEL", "ARMHF"]
    name = "jmpsp"
    asm = "blx sp;"
    code = b"\x3d\xff\x2f\xe1"


class MIPS32JmpSP(Shellcode):
    os = ["unix"]
    arches = ["mipsel", "mipsbe"]
    name = "jmpsp"
    asm = "jalr sp; add $t7, $t7, $zero;"
    code_le = b"\x09\xf8\xa0\x03\x20\x78\xe0\x01"
    code_be = b"\x03\xa0\xf8\x09\x01\xe0\x78\x20"

    def raw(self, arch=None):

        arch = convert_arch(arch)

        if arch.memory_endness == Endness.LE:
            return self.code_le
        else:
            return self.code_be
